/* authentication related services */

var express = require('express')
var router = express.Router(),
    rp = require('request-promise'),
    debug = require('debug')('react-demo')

var configFile = 'config.'+process.env.NODE_ENV+'.json'
var config = require('../../config/'+configFile);
//var App = React.createFactory(main.App);

router.get("/", function(req, res, next){
  var list = [];
  for (var i = 0; i < 7; i++) {
    list.push({
      "id": i,
      "created_at": "2016年6月15日",
      "title": "旅行中, 如何在朋友圈优雅地秀人生",
      "image": "/public/img/asset_image.png",
      "digest": "端午小假期终于要到了"
    })
  }

  return res.json({
    data: list
  });
})

router.post("/", function(req, res, next) {
  var token = req.cookies.access_token;
  var app_id = req.cookies.appId;
  var option = {
    method: 'POST',
    uri: config.apiHost+'/wxapi/asset/batchget_material?app_id='+app_id,
    body: req.body,
    headers: {
      authorization: 'Bearer '+token
    },
    json: true
  }

  rp(option)
    .then(function(result) {
      debug(result);
      // var data = JSON.parse(result)
      return res.json(result)
    })
    .catch(function(err) {
      console.error(err);
      return res.status(err.statusCode).json({
        success: false,
        errCode: err.statusCode
      })
    })
})

router.post("/queryById", function(req, res, next) {
  var token = req.cookies.access_token;
  var appId = req.cookies.appId
  var option = {
    method: 'POST',
    uri: config.apiHost+'/wxapi/asset?app_id='+appId,
    body: req.body,
    headers: {
      authorization: 'Bearer '+token
    },
    json: true
  }

  rp(option)
    .then(function(result) {
      debug(result);
      // var data = JSON.parse(result)
      return res.json(result)
    })
    .catch(function(err) {
      console.error(err.errCode);
      return res.status(err.statusCode).json({
        success: false,
        errCode: err.statusCode
      })
    })
})

//appId, media_id
router.post("/getImage", function(req, res, next) {
  var token = req.cookies.access_token;
  var app_id = req.cookies.appId;
  var param = req.body;
  param.appId = app_id
  var option = {
    method: 'POST',
    uri: config.apiHost+'/api/wechatAssets/',
    body: param,
    headers: {
      authorization: 'Bearer '+token
    },
    json: true
  }


  rp(option)
    .then(function(result) {
      debug(result);
      if (result.success) {
        var data = result.data;
        var url = config.publicHost+data;
        result.data = url;
      }
      return res.json(result)
    })
    .catch(function(err) {
      console.log(param)
      console.error(err);
      return res.status(err.statusCode).json({
        success: false,
        errCode: err.statusCode
      })
    })
})


module.exports = router;
